package com.jy.web.diy.controller;

import java.io.File;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

import cn.afterturn.easypoi.entity.vo.MapExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.vo.BaseEntityTypeConstants;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jy.framework.annotation.RequiresAction;
import com.jy.framework.exception.MyException;
import com.jy.framework.utils.FileUtil;
import com.jy.framework.utils.FormatterUtils;
import com.jy.web.diy.entity.AttributeEntity;
import com.jy.web.diy.entity.JsonEntity;
import com.jy.web.diy.service.AttributeService;
import com.jy.web.diy.service.JsonService;
import com.jy.web.file.service.impl.File2Url;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.jy.framework.base.BaseController;

import com.jy.web.diy.entity.BaseInfoEntity;
import com.jy.web.diy.service.BaseInfoService;
import com.jy.framework.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 基础表
 *
 * @author JuiceYan
 * @email JuiceYan@jy.com
 * @date 2018-12-22 20:55:46
 */
@Api(tags = "数据基础表")
@RestController
@RequestMapping("diy/baseinfo")
public class BaseInfoController extends BaseController<BaseInfoService, BaseInfoEntity> {
    @Autowired
    private AttributeService attributeService;
    @Autowired
    private JsonService jsonService;

    @Override
    public R list(@RequestParam Map<String, Object> params, BaseInfoEntity t) {
        return R.ok().put("page", service.getCategoryDataList(params, false));
    }

    @RequestMapping("/attributes")
    @RequiresAction("list")
    public R attributes(AttributeEntity entity) {
        List<Map<String, Object>> attributes = service.getAttributeMaps(entity);
        return R.ok().put("attributes", attributes);
    }

    @Override
    public R info(@PathVariable("id") String id) {
        BaseInfoEntity entity = service.getBaseInfoEntity(id);
        return R.ok().put("entity", entity);
    }


    @Override
    public R save(@RequestBody BaseInfoEntity entity) {
        service.saveBaseInfo(entity);
        return R.ok();
    }


    @Override
    public R update(@RequestBody BaseInfoEntity entity) {
        service.updateBaseInfo(entity);
        return R.ok();
    }


    @Override
    public R exportExcel(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
        export(map, request, response, false);
        return R.ok();
    }

    @Override
    public R template(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
        export(map, request, response, true);
        return R.ok();
    }

    private void export(ModelMap map, HttpServletRequest request, HttpServletResponse response, boolean isTemplate) {
        ExportParams params = new ExportParams("excel数据", "1", ExcelType.XSSF);
        params.setFreezeCol(2);
        Map<String, Object> conditions = new HashMap<>();
        String diyCategoryId = getCategoryId(request);
//                添加通用条件
        conditions.put("categoryId", diyCategoryId);
        List<Map<String, Object>> list = new ArrayList<>();
        if (!isTemplate) {
            list = service.selectValuesMaps((conditions));
        }
        List<ExcelExportEntity> entity = new ArrayList<>();
        List<Map<String, Object>> attributeMaps = service.getAttributeMaps(diyCategoryId);
        List<String> fileTypes = Arrays.asList("5");
        List<String> imgAttributeIds = new ArrayList<>();

        attributeMaps.stream().forEachOrdered(att -> {
            String name = (String) att.get("name");
            String id = String.valueOf(att.get("id"));
            ExcelExportEntity e = new ExcelExportEntity(name, id);
            String type = String.valueOf(att.get("type"));
            if (fileTypes.contains(type)) {
                e.setExportImageType(1);
                e.setHeight(20);
                e.setWidth(40);
                e.setType(BaseEntityTypeConstants.IMAGE_TYPE);
                imgAttributeIds.add(id);
            }
            entity.add(e);
        });

//        处理图片 url 为本地路径
        for (String imgAttributeId : imgAttributeIds) {
            for (Map<String, Object> objectMap : list) {
                Object o = objectMap.get(imgAttributeId);
                if (o !=null){
//              转换路径
                    String realFilePath = File2Url.httpUrl2RealFilePath(String.valueOf(o));
//                    byte[] bytes = null;
//
//                    try {
//                        bytes = FileUtil.toByteArray(realFilePath);
//                    } catch (Exception e) {
//                        log.error("img-"+realFilePath);
//                        log.error(e.getMessage());
//                    }
//                    objectMap.put(imgAttributeId,bytes);
//                    处理不存在文件
                    if (new File(realFilePath).exists()){
                        objectMap.put(imgAttributeId,realFilePath);
                    }else {
                        log.error("不存在 img-"+realFilePath);
                        objectMap.put(imgAttributeId,null);
                    }
                }
            }
        }

        Optional<List<Map<String, Object>>> tableInfo = service.getTableInfo(BaseInfoEntity.class);
        tableInfo.ifPresent(to -> {
            Map<String, String> columnHeader = to.stream().collect(Collectors.toMap(key -> FormatterUtils.toLowerCamel(String.valueOf(key.get("columnName"))), value -> String.valueOf(value.get("columnComment"))));
            columnHeader.entrySet().forEach(ce -> {
                List<String> commonFields = Arrays.asList("createBy", "createTime", "updateBy", "updateTime", "delFlag");
                if (!commonFields.contains(ce.getKey())) {
                    entity.add(new ExcelExportEntity(ce.getValue(), ce.getKey()));
                }
            });
        });
        map.put(MapExcelConstants.MAP_LIST, list);
        map.put(MapExcelConstants.ENTITY_LIST, entity);
        map.put(MapExcelConstants.PARAMS, params);
        map.put(MapExcelConstants.FILE_NAME, "数据导出");
        PoiBaseView.render(map, request, response, MapExcelConstants.EASYPOI_MAP_EXCEL_VIEW);
    }

    @Override
    public R importExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ImportParams params = new ImportParams();
        params.setNeedVerfiy(true);
        params.setTitleRows(1);
        params.setHeadRows(1);
//        params.setDataHanlder(new MapImportHanlder());
        List<Map<String, Object>> list = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, params);
        if (CollectionUtils.isEmpty(list)) {
            throw new MyException("请在excel文件中添加对应数据");
        }
        String diyCategoryId = getCategoryId(request);
        service.saveBatchBaseInfos(list, diyCategoryId, false);
        return R.ok();
    }
//    @Override
//    public void importExcel(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
//        ImportParams params = new ImportParams();
//        params.setNeedVerfiy(true);
//        params.setTitleRows(1);
//        params.setHeadRows(1);
////        params.setDataHanlder(new MapImportHanlder());
//        List<Map<String, Object>> list = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, params);
//        if (CollectionUtils.isEmpty(list)) {
//            throw new MyException("请在excel文件中添加对应数据");
//        }
//        String diyCategoryId = getCategoryId(request);
//        service.saveBatchBaseInfos(list, diyCategoryId, false);
//        String url = request.getRequestURI();
////        此种方式取不到值
////        System.out.println("categoryId_"+request.getAttribute("diyCategoryId"));
//        String basePath = url.substring(0, url.indexOf("/", 1));
//        String pageName = BaseInfoEntity.class.getSimpleName().replace("Entity", "").toLowerCase();
//
//        response.sendRedirect("/index.html#modules" + basePath + "/" + pageName + ".html?categoryId=" + diyCategoryId);
//    }

    private String getCategoryId(HttpServletRequest request) {
        String[] diyCategoryIds = request.getParameterMap().get("diyCategoryId");
        return diyCategoryIds[0];
    }
}
